package com.jasiri.project.app

import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.jasiri.project.utils.event.EventType
import com.jasiri.project.utils.event.track.TrackEventManager
import com.jasiri.project.utils.helper.ActivityStackHelper
import com.jasiri.project.utils.log.HHLog

/**
 * 用于监听应用前后台切换埋点
 */
class AppLifecycleObserver: DefaultLifecycleObserver {
    private var isBackground = false // 是否处于后台
    override fun onStart(owner: LifecycleOwner) {
        super.onStart(owner)
        if (isBackground) {
            isBackground = false
            var curtPageName = App.curtPageRemark
            if (curtPageName.isEmpty()){
                val curtPage = ActivityStackHelper.getCurrentActivity()
                curtPage?.let {
                    curtPageName = it.javaClass.simpleName
                }
            }
            HHLog.e("LifecycleObserver>>>>>>>>>>in foreground>>>>>>${curtPageName}")
            TrackEventManager.trackEvent(EventType.PAGE.APP_IN_FOREGROUND, curtPageName)
        }
    }

    override fun onStop(owner: LifecycleOwner) {
        super.onStop(owner)
        if (!isBackground) {
            isBackground = true
            var curtPageName = App.curtPageRemark
            if (curtPageName.isEmpty()){
                val curtPage = ActivityStackHelper.getCurrentActivity()
                curtPage?.let {
                    curtPageName = it.javaClass.simpleName
                }
            }
            HHLog.e("LifecycleObserver>>>>>>>>>>in background>>>>>>${curtPageName}")
            TrackEventManager.trackEvent(EventType.PAGE.APP_IN_BACKGROUND,curtPageName)
        }
    }
}